package com.platform.service.impl;

import com.platform.annotation.SysLog;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.common.TokenCache;
import com.platform.dao.UserMapper;
import com.platform.pojo.User;
import com.platform.service.ISendMessageSeivice;
import com.platform.service.IUserService;
import com.platform.util.MD5Util;
import com.platform.util.NumberUtil;
import com.platform.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService,Serializable {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ISendMessageSeivice iSendMessageSeivice;

    @Cacheable("findAllUserData")
    @Override
    @SysLog("测试")
    public ServerResponse findAllUserData(Integer pageNo,Integer pageSize,String orderBy) {
       /* //分页插件
        PageHelper.startPage(pageNo,pageSize,orderBy);
        List<Map> resultList = userMapper.findAllUserData();//数据库查询
        PageInfo pageInfo = new PageInfo(resultList);
        pageInfo.setList(resultList);*/
        return ServerResponse.createBySuccess("查询成功",null);
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    @SysLog("登录")
    public ServerResponse<User> login(String username, String password) {
        //检测用户名是否存在
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0 ){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        //加密密码
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user  = userMapper.selectLogin(username,md5Password);
        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @SysLog("注册")
    public ServerResponse<String> register(User user){
        //检测用户名是否存在
        ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        //检测邮箱是否存在
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        //检测手机号码是否存在
        validResponse = this.checkValid(user.getEmail(),Const.PHONE);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        /*user.setRole(Const.Role.ROLE_CUSTOMER);*/
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    /**
     * 检测相关选项
     * @param str
     * @param type
     * @return
     */
    public ServerResponse<String> checkValid(String str,String type){
        if(org.apache.commons.lang3.StringUtils.isNotBlank(type)){
            //开始校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
            if(Const.PHONE.equals(type)){
                int resultCount = userMapper.checkPhone(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("手机号已被注册");
                }
            }
        }else{
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    /**
     * 更新用户信息
     * @param userMap
     * @return
     */
    @SysLog("更新用户信息")
    public ServerResponse<User> updateInformation(Map userMap){
        //username是不能被更新的
        //email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
        int resultCount = userMapper.checkEmailByUserId(StringUtil.valueOfString(userMap.get("email")),
                NumberUtil.safeToNumber(userMap.get("id")));
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");
        }
        User updateUser = new User();
        updateUser.setId( NumberUtil.safeToNumber(userMap.get("id")));
        updateUser.setEmail(StringUtil.valueOfString(userMap.get("email")));
        updateUser.setPhone(StringUtil.valueOfString(userMap.get("phone")));
        updateUser.setDisplayName(StringUtil.valueOfString(userMap.get("displayName")));
        updateUser.setRemark(StringUtil.valueOfString(userMap.get("remark")));
        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    @Override
    @SysLog("修改密码前发送验证码")
    public ServerResponse<String> updatePasswordSendMessageCode(Map param, HttpServletRequest request) {
        String phoneNumber = StringUtil.valueOfString(param.get("phoneNumber"));
        String username = StringUtil.valueOfString(param.get("username"));
        if(StringUtil.isEmpty(phoneNumber)){
            return ServerResponse.createByErrorMessage("操作失败");
        }
        //查询此手机号跟传入用户名是否匹配
        if(NumberUtil.safeToNumber(userMapper.selectByPhoneAndUsername(phoneNumber,username)) <= 0){
            return ServerResponse.createByErrorMessage("注册手机号和账户不匹配");
        }
        //发送验证码
        iSendMessageSeivice.sendMessage(param,request);
        //存入tonken值
        String forgetToken = UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PREFIX+username+phoneNumber,forgetToken);
        return ServerResponse.createBySuccessMessage(forgetToken);
    }

    /**
     * 修改密码
     * @param param
     * @param request
     * @return
     */
    @Override
    @SysLog("修改密码")
    public ServerResponse<String> forgetRestPassword(Map param,HttpServletRequest request) {
        //获取传入验证码
        String codestr = StringUtil.valueOfString(param.get("vCode"));
        if(StringUtil.isEmpty(codestr)){
            return ServerResponse.createByErrorMessage("验证码不能为空");
        }
        //获取session验证码
        String localCode = StringUtil.valueOfString(request.getSession().getAttribute(Const.CodeType.PHONECODE));
        if(!codestr.toLowerCase().equals(localCode.toLowerCase())){
            return ServerResponse.createByErrorMessage("验证码不正确！");
        }
        //获取传入token值
        String forgetToken = StringUtil.valueOfString(param.get("tokenValue"));
        if(StringUtil.isEmpty(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        //获取传入手机号
        String phoneNumber = StringUtil.valueOfString(param.get("phone"));
        //根据手机号获取本地token值
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+StringUtil.valueOfString(param.get("username"))+phoneNumber);
        if(StringUtil.isEmpty(token)){
            return ServerResponse.createByErrorMessage("参数失效");
        }
        if(forgetToken.equals(token)){
            //tonKen对上 修改密码
            String md5Password  = MD5Util.MD5EncodeUtf8(StringUtil.valueOfString(param.get("password")));
            int rowCount = userMapper.updatePasswordByUsername(StringUtil.valueOfString(param.get("username")),
                    md5Password);
            if(rowCount > 0){
                return ServerResponse.createBySuccessMessage("修改成功");
            }
        }
        return ServerResponse.createByErrorMessage("修改失败");
    }


    /**
     * 根据用户名或角色查询用户
     * @param role
     * @param displayName
     * @return
     */
    public ServerResponse<List<Map>> selectByUserRole(String role,String displayName){
        return null;
    }

}
